package com.jpcc.vw.onlineRadio.adapter;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.action.DeletePlayHistoryAction;
import com.jpcc.vw.onlineRadio.model.action.DownloadTrackAction2;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.DownloadInfo;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.jpcc.vw.onlineRadio.utils.ViewHolderUtils;
import com.jpcc.vw.onlineRadio.widget.Indicator;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.lzy.okhttpserver.download.DownloadManager;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


public class PlayHistoryAdapter extends BaseAdapter {


    private List<RecentAlbumRadioTrackBean> results = new ArrayList<>();
    private Context context;
    private DownloadManager downloadManager;

    public PlayHistoryAdapter(List<RecentAlbumRadioTrackBean> datas, Context c) {
        if (datas != null) {
            results.clear();
            results.addAll(datas);
            this.context = c;
        }
    }

    public void setDatas(List<RecentAlbumRadioTrackBean> datas) {
        if (datas != null) {
            results.clear();
            results.addAll(datas);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return results.size();
    }

    @Override
    public Object getItem(int position) {
        return results.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_play_history, parent, false);
        }
        initViews(convertView, position);
        return convertView;
    }

    private void initViews(View convertView, int position) {
        RecentAlbumRadioTrackBean entity = results.get(position);
        TextView tv_item_count = ViewHolderUtils.get(convertView, R.id.tv_item_count);
        TextView tv_title = ViewHolderUtils.get(convertView, R.id.tv_title);
        TextView tv_program_name = ViewHolderUtils.get(convertView, R.id.tv_program_name);
        ImageView imv_delete = ViewHolderUtils.get(convertView, R.id.imv_delete);
        ImageView imv_download = ViewHolderUtils.get(convertView, R.id.imv_download);
//        Indicator imv_playing = ViewHolderUtils.get(convertView, R.id.imv_playing);
        ImageView imv_play_status=ViewHolderUtils.get(convertView,R.id.imv_play_status);
        RelativeLayout layout_bg = ViewHolderUtils.get(convertView, R.id.layout_bg);
        View imv_divider = ViewHolderUtils.get(convertView, R.id.imv_divider);
        tv_item_count.setVisibility(View.GONE);
        tv_item_count.setText(position + 1 + "");
        tv_title.setText(entity.getAlbumName());
        tv_program_name.setText(entity.getTrackName());
        imv_delete.setVisibility(View.VISIBLE);
        String bgColor = "#404040";
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(context).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(context).getHmiAtmosphereLampColor();
                if (atmosphereStatus) {
                    if (!TextUtils.isEmpty(color)) {
                        bgColor = color;
                    }
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


//        if (AlbumRadioAudioPlayer.get().isPlaying() || AlbumRadioAudioPlayer.get().isPreparing()) {
//            imv_playing.setIndicatorPause(true);
//        } else {
//            imv_playing.setIndicatorPause(false);
//        }


//        if(AlbumRadioAudioPlayer.get().isPausing()){
//            imv_playing.setIndicatorPause(false);
//        }
//        else{
//            imv_playing.setIndicatorPause(true);
//        }


        if ("album".equals(entity.getType()) && !TextUtils.isEmpty(entity.getDownloadUrl())) {
            String path_local = TrackUtils.getTrackDir() + entity.getAlbumId() + entity.getTrackId() + "." + entity.getDownloadUrl().substring(entity.getDownloadUrl().length() - 3, entity.getDownloadUrl().length());
//            byte downloadStatus= FileDownloader.getImpl().getStatus(entity.getDownloadUrl(),path_local);
            if (downloadManager == null) {
                downloadManager = DownloadManager.getInstance(context);
            }
            com.lzy.okhttpserver.download.DownloadInfo downloadInfo = downloadManager.getTaskByUrl(entity.getDownloadUrl());
            imv_divider.setVisibility(View.VISIBLE);
            if (downloadInfo != null) {
                if (downloadInfo.getState() == DownloadManager.NONE) {
                    imv_download.setImageResource(R.drawable.detail_not_download);
                    imv_divider.setVisibility(View.VISIBLE);
                    imv_download.setVisibility(View.VISIBLE);
                } else if (downloadInfo.getState() == DownloadManager.WAITING || downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                    imv_download.setImageResource(R.drawable.detail_loading);
                    imv_divider.setVisibility(View.VISIBLE);
                    imv_download.setVisibility(View.VISIBLE);
                } else if (downloadInfo.getState() == DownloadManager.FINISH) {
                    imv_download.setImageResource(R.drawable.detail_success);
                    imv_divider.setVisibility(View.VISIBLE);
                    imv_download.setVisibility(View.VISIBLE);
                }
                else{
                    imv_download.setImageResource(R.drawable.detail_not_download);
                    imv_divider.setVisibility(View.VISIBLE);
                    imv_download.setVisibility(View.VISIBLE);
                }
            } else {
                imv_download.setImageResource(R.drawable.detail_not_download);
                imv_divider.setVisibility(View.VISIBLE);
                imv_download.setVisibility(View.VISIBLE);
            }
            if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
                if (AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() == entity.getAlbumId() && AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() == entity.getTrackId()) {
//                    imv_playing.setVisibility(View.VISIBLE);
                    imv_play_status.setVisibility(View.VISIBLE);
                    layout_bg.setBackgroundColor(Color.parseColor("#000000"));
                } else {
//                    imv_playing.setVisibility(View.GONE);
                    imv_play_status.setVisibility(View.GONE);
                    layout_bg.setBackgroundColor(Color.parseColor("#000000"));
                }
            } else {
//                imv_playing.setVisibility(View.GONE);
                imv_play_status.setVisibility(View.GONE);
                layout_bg.setBackgroundColor(Color.parseColor("#000000"));
            }
        }else if("album".equals(entity.getType()) && TextUtils.isEmpty(entity.getDownloadUrl())){
            imv_divider.setVisibility(View.VISIBLE);
            imv_download.setVisibility(View.VISIBLE);
            imv_download.setImageResource(R.drawable.detail_not_download);
            if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
                if (AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() == entity.getAlbumId() && AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() == entity.getTrackId()) {
//                    imv_playing.setVisibility(View.VISIBLE);
                    imv_play_status.setVisibility(View.VISIBLE);
                    layout_bg.setBackgroundColor(Color.parseColor("#000000"));
                } else {
//                    imv_playing.setVisibility(View.GONE);
                    imv_play_status.setVisibility(View.GONE);
                    layout_bg.setBackgroundColor(Color.parseColor("#000000"));
                }
            } else {
//                imv_playing.setVisibility(View.GONE);
                imv_play_status.setVisibility(View.GONE);
                layout_bg.setBackgroundColor(Color.parseColor("#000000"));
            }
        }
        else {
            imv_download.setVisibility(View.INVISIBLE);
            imv_divider.setVisibility(View.INVISIBLE);
            if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
                if (AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() == entity.getAlbumId()) {
//                    imv_playing.setVisibility(View.VISIBLE);
                    imv_play_status.setVisibility(View.VISIBLE);
                    layout_bg.setBackgroundColor(Color.parseColor("#000000"));
                } else {
//                    imv_playing.setVisibility(View.GONE);
                    imv_play_status.setVisibility(View.GONE);
                    layout_bg.setBackgroundColor(Color.parseColor("#000000"));
                }
            } else {
//                imv_playing.setVisibility(View.GONE);
                imv_play_status.setVisibility(View.GONE);
                layout_bg.setBackgroundColor(Color.parseColor("#000000"));
            }
        }


        if (AlbumRadioAudioPlayer.get().isPlaying() || AlbumRadioAudioPlayer.get().isPreparing()) {
//                imv_playing.setIndicatorPause(true);
            imv_play_status.setImageResource(R.drawable.ic_play_in_list);
        } else {
//                imv_playing.setIndicatorPause(false);
            imv_play_status.setImageResource(R.drawable.ic_pause_in_list);
        }


        imv_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(entity.getDownloadUrl())){
                    ToastUtils.show(R.string.string_95);
                    return;
                }
                String path = TrackUtils.getTrackDir() + entity.getAlbumId() + entity.getTrackId() + "." + entity.getDownloadUrl().substring(entity.getDownloadUrl().length() - 3, entity.getDownloadUrl().length());
                File file = new File(path);
                Logger.i("path-->" + path);
                if (file.exists()) {
                    ToastUtils.show(R.string.string_114);
                    return;
                }
                DownloadTrackAction2 action = new DownloadTrackAction2();
                Track track = new Track();
                track.setId(entity.getTrackId());
                track.setDownloadUrl(entity.getDownloadUrl());
                SubordinatedAlbum album = new SubordinatedAlbum();
                album.setId(entity.getAlbumId());
                album.setAlbumTitle(entity.getAlbumName());
                album.setCoverUrlLarge(entity.getCover());
                Announcer announcer = new Announcer();
                announcer.setNickname("");
                track.setTrackTitle(entity.getTrackName());
                track.setDuration(entity.getDuration());
                track.setAnnouncer(announcer);
                track.setSubordinatedAlbum(album);
                action.setTrack(track);
                action.setDir(TrackUtils.getTrackDir());
                action.setFileName(entity.getAlbumId() + entity.getTrackId() + "." + entity.getDownloadUrl().substring(entity.getDownloadUrl().length() - 3, entity.getDownloadUrl().length()));
                EventBus.getDefault().post(action);

            }
        });
        imv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!Constants.isRelease){
                    MaterialDialog dialog = new MaterialDialog.Builder(context).title(context.getResources().getString(R.string.string_30)).content(context.getResources().getString(R.string.string_119)).positiveText(context.getResources().getString(R.string.string_32)).negativeText(context.getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            List<RecentAlbumRadioTrackBean> results_local = new ArrayList<>();
                            DeletePlayHistoryAction action = new DeletePlayHistoryAction();
                            action.setAlbumId(entity.getAlbumId());
                            action.setTrackId(entity.getTrackId());
                            if ("album".equals(entity.getType())) {
                                for (RecentAlbumRadioTrackBean bean : results) {
                                    if ((entity.getTrackId() != bean.getTrackId())) {
                                        results_local.add(bean);
                                    }
                                }
                                action.setContentType(1);
                            } else {
                                for (RecentAlbumRadioTrackBean bean : results) {
                                    if ((entity.getTrackId() != bean.getTrackId())) {
                                        results_local.add(bean);
                                    }
                                    action.setContentType(2);
                                }
                            }
                            EventBus.getDefault().post(action);
                        }
                    }).build();
                    dialog.show();
                }
                else{
//                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//                    Intent setAlertIntent = new Intent("com.jpcc.vw.PlayHistoryActivity");
//                    setAlertIntent.putExtra("action", "DeleteSpecificHistory");
//                    if ("album".equals(entity.getType())) {
//                        setAlertIntent.putExtra("ContentType",1);
//                    }
//                    else{
//                        setAlertIntent.putExtra("ContentType",2);
//                    }
//                    setAlertIntent.putExtra("AlbumId",entity.getAlbumId());
//                    setAlertIntent.putExtra("TrackId",entity.getTrackId());
//                    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//                    Popup popup = new Popup(context.getResources().getString(R.string.string_30), context.getResources().getString(R.string.string_119));
//                    popup.setActionOne(context.getResources().getString(R.string.string_32), pendingIntent);
//                    popup.setActionCancel(context.getResources().getString(R.string.string_33), "cancel");
//                    notificationManager.addPopup(0x0005, popup);


                    List<RecentAlbumRadioTrackBean> results_local = new ArrayList<>();
                    DeletePlayHistoryAction action = new DeletePlayHistoryAction();
                    action.setAlbumId(entity.getAlbumId());
                    action.setTrackId(entity.getTrackId());
                    if ("album".equals(entity.getType())) {
                        for (RecentAlbumRadioTrackBean bean : results) {
                            if ((entity.getTrackId() != bean.getTrackId())) {
                                results_local.add(bean);
                            }
                        }
                        action.setContentType(1);
                    } else {
                        for (RecentAlbumRadioTrackBean bean : results) {
                            if ((entity.getTrackId() != bean.getTrackId())) {
                                results_local.add(bean);
                            }
                            action.setContentType(2);
                        }
                    }
                    EventBus.getDefault().post(action);







                }
            }
        });
    }
}
